//
//  UIColor+PPKit.swift
//  PPKit
//
//  Created by xiaopin on 16/8/31.
//  Copyright © 2016年 pinguo. All rights reserved.
//  https://gitee.com/xiaopindev/PPKit
//  https://github.com/xiaopindev
//  https://xiaopin.cnblogs.com

import UIKit

extension UIColor {
    
    /// 初始化16进制的样色
    /// - Parameters:
    ///   - hex: "FFFFFF" || "#FFFFFF"
    class func hexColor(_ hex:String?, alpha: CGFloat = 1) -> UIColor {
        guard let hex = hex else {
            return UIColor.clear
        }
        
        var cstr = hex.trimmingCharacters(in:CharacterSet.whitespacesAndNewlines).uppercased() as NSString
        if(cstr.hasPrefix("#")){
            cstr = cstr.substring(from: 1) as NSString
        }
        
        if cstr.length != 6 && cstr.length != 3 {
            return UIColor.clear
        }

        var range = NSRange.init()
        range.location = 0
        range.length = 2
        
        //r
        var rStr = ""
        //g
        var gStr = ""
        //b
        var bStr = ""
        
        if cstr.length == 6 {
            rStr = cstr.substring(with: range)
            
            range.location = 2
            gStr = cstr.substring(with: range)
            
            range.location = 4
            bStr = cstr.substring(with: range)
            
        } else if cstr.length == 3 {
            range.length = 1
            rStr = cstr.substring(with: range)
            rStr = rStr + rStr
            
            range.location = 1
            gStr = cstr.substring(with: range)
            gStr = gStr + gStr
            
            range.location = 2
            bStr = cstr.substring(with: range)
            bStr = bStr + bStr
        }
        
        var r :UInt32 = 0x0
        var g :UInt32 = 0x0
        var b :UInt32 = 0x0
        Scanner.init(string: rStr).scanHexInt32(&r)
        Scanner.init(string: gStr).scanHexInt32(&g)
        Scanner.init(string: bStr).scanHexInt32(&b)
        
        return UIColor(red: CGFloat(Double(r)/255.0),
                       green: CGFloat(Double(g)/255.0),
                       blue: CGFloat(Double(b)/255.0),
                       alpha: alpha)
    }
    
    //返回随机颜色
    open class var randomColor:UIColor{
        get
        {
            let red = CGFloat(arc4random()%256)/255.0
            let green = CGFloat(arc4random()%256)/255.0
            let blue = CGFloat(arc4random()%256)/255.0
            return UIColor(red: red, green: green, blue: blue, alpha: 1.0)
        }
    }
    
    //    var toHexString: String {
    //        var r: CGFloat = 0
    //        var g: CGFloat = 0
    //        var b: CGFloat = 0
    //        var a: CGFloat = 1
    //
    //        self.getRed(&r, green: &g, blue: &b, alpha: &a)
    //
    //        return String(
    //            format: "%02X%02X%02X",
    //            Int(r * 0xff),
    //            Int(g * 0xff),
    //            Int(b * 0xff)
    //        )
    //    }
    
}
